<template>
  <div class="image-watermark-tool">
    <div class="tool-header">
      <h1>图片水印工具</h1>
      <p>为图片添加文字或图片水印</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 上传区域 -->
        <el-col :span="12">
          <div class="upload-section">
            <div class="section-header">
              <h3>上传图片</h3>
            </div>
            
            <div class="upload-area">
              <el-upload
                ref="uploadRef"
                class="upload-dragger"
                drag
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleFileChange"
                accept="image/*"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  将图片拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 JPG、PNG、GIF、WebP 格式
                  </div>
                </template>
              </el-upload>
            </div>
            
            <div class="file-info" v-if="originalFile">
              <h4>原始图片信息</h4>
              <div class="info-grid">
                <div class="info-item">
                  <span class="label">文件名：</span>
                  <span class="value">{{ originalFile.name }}</span>
                </div>
                <div class="info-item">
                  <span class="label">文件大小：</span>
                  <span class="value">{{ formatFileSize(originalFile.size) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">图片尺寸：</span>
                  <span class="value">{{ originalImageSize }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 水印设置和结果 -->
        <el-col :span="12">
          <div class="watermark-section">
            <div class="section-header">
              <h3>水印设置</h3>
            </div>
            
            <div class="watermark-options" v-if="originalFile">
              <div class="option-group">
                <label>水印类型：</label>
                <el-radio-group v-model="watermarkType" @change="handleTypeChange">
                  <el-radio label="text">文字水印</el-radio>
                  <el-radio label="image">图片水印</el-radio>
                </el-radio-group>
              </div>
              
              <!-- 文字水印设置 -->
              <div v-if="watermarkType === 'text'">
                <div class="option-group">
                  <label>水印文字：</label>
                  <el-input
                    v-model="watermarkText"
                    placeholder="输入水印文字"
                    maxlength="50"
                    show-word-limit
                  />
                </div>
                
                <div class="option-group">
                  <label>字体设置：</label>
                  <div class="font-settings">
                    <el-select v-model="fontFamily" placeholder="选择字体" style="width: 120px;">
                      <el-option label="Arial" value="Arial" />
                      <el-option label="微软雅黑" value="Microsoft YaHei" />
                      <el-option label="宋体" value="SimSun" />
                      <el-option label="黑体" value="SimHei" />
                      <el-option label="楷体" value="KaiTi" />
                    </el-select>
                    <el-input-number
                      v-model="fontSize"
                      :min="12"
                      :max="200"
                      controls-position="right"
                      placeholder="字号"
                      style="width: 100px;"
                    />
                    <el-color-picker v-model="fontColor" />
                  </div>
                </div>
              </div>
              
              <!-- 图片水印设置 -->
              <div v-if="watermarkType === 'image'">
                <div class="option-group">
                  <label>水印图片：</label>
                  <el-upload
                    ref="watermarkUploadRef"
                    class="watermark-upload"
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="handleWatermarkImageChange"
                    accept="image/*"
                  >
                    <el-button type="primary" plain>
                      <el-icon><Upload /></el-icon>
                      选择水印图片
                    </el-button>
                  </el-upload>
                  <div class="watermark-preview" v-if="watermarkImage">
                    <img :src="watermarkImageUrl" alt="水印预览" />
                  </div>
                </div>
                
                <div class="option-group">
                  <label>水印尺寸：</label>
                  <div class="watermark-size">
                    <el-input-number
                      v-model="watermarkWidth"
                      :min="20"
                      :max="500"
                      controls-position="right"
                      placeholder="宽度"
                    />
                    <span class="separator">×</span>
                    <el-input-number
                      v-model="watermarkHeight"
                      :min="20"
                      :max="500"
                      controls-position="right"
                      placeholder="高度"
                    />
                    <el-checkbox v-model="maintainWatermarkRatio" @change="handleWatermarkRatioChange">
                      保持比例
                    </el-checkbox>
                  </div>
                </div>
              </div>
              
              <div class="option-group">
                <label>水印位置：</label>
                <div class="position-grid">
                  <div 
                    v-for="position in positions" 
                    :key="position.value"
                    class="position-item"
                    :class="{ active: watermarkPosition === position.value }"
                    @click="watermarkPosition = position.value"
                  >
                    <el-icon><component :is="position.icon" /></el-icon>
                    <span>{{ position.label }}</span>
                  </div>
                </div>
              </div>
              
              <div class="option-group">
                <label>透明度：</label>
                <el-slider
                  v-model="opacity"
                  :min="10"
                  :max="100"
                  :step="5"
                  show-input
                  :show-input-controls="false"
                />
              </div>
              
              <div class="option-group">
                <label>水印间距：</label>
                <div class="spacing-settings">
                  <el-input-number
                    v-model="marginX"
                    :min="0"
                    :max="200"
                    controls-position="right"
                    placeholder="水平间距"
                  />
                  <span class="separator">×</span>
                  <el-input-number
                    v-model="marginY"
                    :min="0"
                    :max="200"
                    controls-position="right"
                    placeholder="垂直间距"
                  />
                </div>
              </div>
              
              <div class="option-group">
                <label>重复模式：</label>
                <el-radio-group v-model="repeatMode">
                  <el-radio label="single">单个水印</el-radio>
                  <el-radio label="repeat">重复水印</el-radio>
                  <el-radio label="diagonal">对角线重复</el-radio>
                </el-radio-group>
              </div>
            </div>
            
            <div class="watermark-actions" v-if="originalFile">
              <el-button 
                type="primary" 
                @click="addWatermark"
                :loading="isProcessing"
                :disabled="!canProcess"
                size="large"
              >
                <el-icon><Edit /></el-icon>
                添加水印
              </el-button>
              <el-button @click="resetAll" size="large">重置</el-button>
            </div>
            
            <!-- 处理结果 -->
            <div class="result-section" v-if="watermarkedFile">
              <div class="section-header">
                <h3>处理结果</h3>
              </div>
              
              <div class="result-info">
                <div class="comparison">
                  <div class="comparison-item">
                    <h4>原图</h4>
                    <div class="file-size">{{ formatFileSize(originalFile.size) }}</div>
                  </div>
                  <div class="comparison-item">
                    <h4>加水印后</h4>
                    <div class="file-size">{{ formatFileSize(watermarkedFile.size) }}</div>
                  </div>
                </div>
              </div>
              
              <div class="result-actions">
                <el-button @click="downloadWatermarked" type="primary" size="large">
                  <el-icon><Download /></el-icon>
                  下载图片
                </el-button>
                <el-button @click="previewImage" size="large">
                  <el-icon><View /></el-icon>
                  预览图片
                </el-button>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 使用说明 -->
      <div class="tool-info">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>使用说明</span>
            </div>
          </template>
          
          <div class="info-content">
            <h4>水印类型：</h4>
            <ul>
              <li><strong>文字水印：</strong>添加文字标识，可自定义字体、颜色、大小</li>
              <li><strong>图片水印：</strong>添加图片标识，如Logo、签名等</li>
            </ul>
            
            <h4>位置选择：</h4>
            <ul>
              <li><strong>角落位置：</strong>左上、右上、左下、右下，适合Logo</li>
              <li><strong>边缘位置：</strong>上中、下中、左中、右中，适合文字</li>
              <li><strong>中心位置：</strong>居中，适合透明水印</li>
            </ul>
            
            <h4>重复模式：</h4>
            <ul>
              <li><strong>单个水印：</strong>只添加一个水印</li>
              <li><strong>重复水印：</strong>按网格重复添加水印</li>
              <li><strong>对角线重复：</strong>沿对角线重复添加水印</li>
            </ul>
            
            <h4>使用建议：</h4>
            <ul>
              <li>透明度建议设置在30-70%之间</li>
              <li>文字水印建议使用简洁的文字</li>
              <li>图片水印建议使用PNG格式的透明背景图片</li>
              <li>水印大小不要超过原图的1/4</li>
            </ul>
            
            <h4>注意事项：</h4>
            <div class="warning">
              <p>⚠️ 添加水印后的图片仅在前端处理，不会上传到服务器</p>
              <p>⚠️ 水印会永久添加到图片中，无法单独移除</p>
              <p>⚠️ 建议先备份原始图片</p>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  UploadFilled, 
  Upload, 
  Edit, 
  Download, 
  View,
  TopLeft,
  Top,
  TopRight,
  ArrowLeft,
  ArrowRight,
  BottomLeft,
  Bottom,
  BottomRight,
  Position
} from '@element-plus/icons-vue'

const uploadRef = ref()
const watermarkUploadRef = ref()
const originalFile = ref(null)
const watermarkedFile = ref(null)
const watermarkImage = ref(null)
const watermarkImageUrl = ref('')
const originalImageSize = ref('')
const watermarkType = ref('text')
const watermarkText = ref('')
const fontFamily = ref('Arial')
const fontSize = ref(24)
const fontColor = ref('#FFFFFF')
const watermarkWidth = ref(100)
const watermarkHeight = ref(50)
const maintainWatermarkRatio = ref(true)
const watermarkPosition = ref('bottom-right')
const opacity = ref(70)
const marginX = ref(20)
const marginY = ref(20)
const repeatMode = ref('single')
const isProcessing = ref(false)

const positions = [
  { value: 'top-left', label: '左上', icon: 'TopLeft' },
  { value: 'top', label: '上中', icon: 'Top' },
  { value: 'top-right', label: '右上', icon: 'TopRight' },
  { value: 'left', label: '左中', icon: 'ArrowLeft' },
  { value: 'center', label: '居中', icon: 'Position' },
  { value: 'right', label: '右中', icon: 'ArrowRight' },
  { value: 'bottom-left', label: '左下', icon: 'BottomLeft' },
  { value: 'bottom', label: '下中', icon: 'Bottom' },
  { value: 'bottom-right', label: '右下', icon: 'BottomRight' }
]

const canProcess = computed(() => {
  if (watermarkType.value === 'text') {
    return watermarkText.value.trim() !== ''
  } else {
    return watermarkImage.value !== null
  }
})

const handleFileChange = (file) => {
  const fileObj = file.raw
  if (!fileObj) return
  
  if (!fileObj.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }
  
  originalFile.value = fileObj
  
  // 获取图片尺寸
  const img = new Image()
  img.onload = () => {
    originalImageSize.value = `${img.width} × ${img.height}`
  }
  img.src = URL.createObjectURL(fileObj)
  
  ElMessage.success('图片上传成功')
}

const handleTypeChange = () => {
  // 重置相关设置
  watermarkText.value = ''
  watermarkImage.value = null
  watermarkImageUrl.value = ''
}

const handleWatermarkImageChange = (file) => {
  const fileObj = file.raw
  if (!fileObj) return
  
  if (!fileObj.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }
  
  watermarkImage.value = fileObj
  watermarkImageUrl.value = URL.createObjectURL(fileObj)
  
  // 获取水印图片尺寸
  const img = new Image()
  img.onload = () => {
    watermarkWidth.value = Math.min(img.width, 200)
    watermarkHeight.value = Math.min(img.height, 100)
  }
  img.src = watermarkImageUrl.value
  
  ElMessage.success('水印图片上传成功')
}

const handleWatermarkRatioChange = () => {
  if (maintainWatermarkRatio.value && watermarkImage.value) {
    const img = new Image()
    img.onload = () => {
      const ratio = img.width / img.height
      watermarkHeight.value = Math.round(watermarkWidth.value / ratio)
    }
    img.src = watermarkImageUrl.value
  }
}

const addWatermark = async () => {
  if (!originalFile.value) {
    ElMessage.warning('请先上传图片')
    return
  }
  
  if (!canProcess.value) {
    ElMessage.warning('请设置水印内容')
    return
  }
  
  isProcessing.value = true
  
  try {
    // 模拟处理过程
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    const img = new Image()
    
    img.onload = () => {
      canvas.width = img.width
      canvas.height = img.height
      
      // 绘制原图
      ctx.drawImage(img, 0, 0)
      
      // 设置透明度
      ctx.globalAlpha = opacity.value / 100
      
      if (watermarkType.value === 'text') {
        addTextWatermark(ctx, canvas.width, canvas.height)
      } else {
        addImageWatermark(ctx, canvas.width, canvas.height)
      }
      
      // 重置透明度
      ctx.globalAlpha = 1
      
      canvas.toBlob((blob) => {
        watermarkedFile.value = blob
        isProcessing.value = false
        ElMessage.success('水印添加完成')
      }, originalFile.value.type, 0.9)
    }
    
    img.src = URL.createObjectURL(originalFile.value)
  } catch (error) {
    isProcessing.value = false
    ElMessage.error('处理失败：' + error.message)
  }
}

const addTextWatermark = (ctx, canvasWidth, canvasHeight) => {
  ctx.font = `${fontSize.value}px ${fontFamily.value}`
  ctx.fillStyle = fontColor.value
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  
  const textWidth = ctx.measureText(watermarkText.value).width
  const textHeight = fontSize.value
  
  if (repeatMode.value === 'single') {
    const position = getWatermarkPosition(canvasWidth, canvasHeight, textWidth, textHeight)
    ctx.fillText(watermarkText.value, position.x, position.y)
  } else {
    addRepeatedWatermark(ctx, canvasWidth, canvasHeight, textWidth, textHeight, () => {
      ctx.fillText(watermarkText.value, 0, 0)
    })
  }
}

const addImageWatermark = (ctx, canvasWidth, canvasHeight) => {
  const watermarkImg = new Image()
  watermarkImg.onload = () => {
    if (repeatMode.value === 'single') {
      const position = getWatermarkPosition(canvasWidth, canvasHeight, watermarkWidth.value, watermarkHeight.value)
      ctx.drawImage(watermarkImg, position.x, position.y, watermarkWidth.value, watermarkHeight.value)
    } else {
      addRepeatedWatermark(ctx, canvasWidth, canvasHeight, watermarkWidth.value, watermarkHeight.value, () => {
        ctx.drawImage(watermarkImg, 0, 0, watermarkWidth.value, watermarkHeight.value)
      })
    }
  }
  watermarkImg.src = watermarkImageUrl.value
}

const getWatermarkPosition = (canvasWidth, canvasHeight, watermarkWidth, watermarkHeight) => {
  const margin = 20
  let x, y
  
  switch (watermarkPosition.value) {
    case 'top-left':
      x = margin
      y = margin
      break
    case 'top':
      x = canvasWidth / 2
      y = margin
      break
    case 'top-right':
      x = canvasWidth - margin
      y = margin
      break
    case 'left':
      x = margin
      y = canvasHeight / 2
      break
    case 'center':
      x = canvasWidth / 2
      y = canvasHeight / 2
      break
    case 'right':
      x = canvasWidth - margin
      y = canvasHeight / 2
      break
    case 'bottom-left':
      x = margin
      y = canvasHeight - margin
      break
    case 'bottom':
      x = canvasWidth / 2
      y = canvasHeight - margin
      break
    case 'bottom-right':
      x = canvasWidth - margin
      y = canvasHeight - margin
      break
    default:
      x = canvasWidth - margin
      y = canvasHeight - margin
  }
  
  return { x, y }
}

const addRepeatedWatermark = (ctx, canvasWidth, canvasHeight, watermarkWidth, watermarkHeight, drawFunction) => {
  const stepX = watermarkWidth + marginX.value
  const stepY = watermarkHeight + marginY.value
  
  if (repeatMode.value === 'repeat') {
    for (let x = 0; x < canvasWidth; x += stepX) {
      for (let y = 0; y < canvasHeight; y += stepY) {
        ctx.save()
        ctx.translate(x, y)
        drawFunction()
        ctx.restore()
      }
    }
  } else if (repeatMode.value === 'diagonal') {
    const diagonalStep = Math.sqrt(stepX * stepX + stepY * stepY)
    for (let i = 0; i < Math.max(canvasWidth, canvasHeight) / diagonalStep; i++) {
      const x = i * stepX
      const y = i * stepY
      if (x < canvasWidth && y < canvasHeight) {
        ctx.save()
        ctx.translate(x, y)
        drawFunction()
        ctx.restore()
      }
    }
  }
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const downloadWatermarked = () => {
  if (!watermarkedFile.value) {
    ElMessage.warning('没有可下载的文件')
    return
  }
  
  const url = URL.createObjectURL(watermarkedFile.value)
  const a = document.createElement('a')
  a.href = url
  a.download = `watermarked_${originalFile.value.name}`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  
  ElMessage.success('文件下载开始')
}

const previewImage = () => {
  if (!watermarkedFile.value) {
    ElMessage.warning('没有可预览的文件')
    return
  }
  
  const url = URL.createObjectURL(watermarkedFile.value)
  window.open(url, '_blank')
}

const resetAll = () => {
  originalFile.value = null
  watermarkedFile.value = null
  watermarkImage.value = null
  watermarkImageUrl.value = ''
  originalImageSize.value = ''
  watermarkType.value = 'text'
  watermarkText.value = ''
  fontFamily.value = 'Arial'
  fontSize.value = 24
  fontColor.value = '#FFFFFF'
  watermarkWidth.value = 100
  watermarkHeight.value = 50
  maintainWatermarkRatio.value = true
  watermarkPosition.value = 'bottom-right'
  opacity.value = 70
  marginX.value = 20
  marginY.value = 20
  repeatMode.value = 'single'
  uploadRef.value?.clearFiles()
  watermarkUploadRef.value?.clearFiles()
  ElMessage.info('已重置所有设置')
}
</script>

<style scoped>
.image-watermark-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.upload-section,
.watermark-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.section-header {
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.upload-area {
  margin-bottom: 20px;
}

.upload-dragger {
  width: 100%;
}

.file-info {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.file-info h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 1.1rem;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #e9ecef;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-weight: 500;
  color: #666;
}

.value {
  color: #333;
  font-family: 'Courier New', monospace;
}

.watermark-options {
  margin-bottom: 30px;
}

.option-group {
  margin-bottom: 25px;
}

.option-group label {
  display: block;
  margin-bottom: 10px;
  font-weight: 500;
  color: #333;
}

.font-settings {
  display: flex;
  align-items: center;
  gap: 10px;
}

.watermark-upload {
  margin-bottom: 10px;
}

.watermark-preview {
  margin-top: 10px;
}

.watermark-preview img {
  max-width: 100px;
  max-height: 50px;
  border: 1px solid #e9ecef;
  border-radius: 4px;
}

.watermark-size {
  display: flex;
  align-items: center;
  gap: 10px;
}

.separator {
  color: #666;
  font-weight: bold;
}

.position-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.position-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px 10px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.position-item:hover {
  border-color: #667eea;
  background: #f0f4ff;
}

.position-item.active {
  border-color: #667eea;
  background: #667eea;
  color: white;
}

.position-item .el-icon {
  font-size: 20px;
  margin-bottom: 5px;
}

.position-item span {
  font-size: 0.8rem;
}

.spacing-settings {
  display: flex;
  align-items: center;
  gap: 10px;
}

.watermark-actions {
  display: flex;
  gap: 12px;
  margin-top: 30px;
}

.result-section {
  margin-top: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.result-info {
  margin-bottom: 20px;
}

.comparison {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.comparison-item {
  text-align: center;
}

.comparison-item h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.file-size {
  font-size: 1.2rem;
  font-weight: bold;
  color: #667eea;
}

.result-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.tool-info {
  margin-top: 40px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.info-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.info-content p {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
}

.info-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.info-content li {
  margin-bottom: 5px;
}

.warning {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
  margin: 15px 0;
}

.warning p {
  margin: 5px 0;
  color: #856404;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .font-settings {
    flex-direction: column;
    align-items: stretch;
  }
  
  .watermark-size {
    flex-direction: column;
    align-items: stretch;
  }
  
  .spacing-settings {
    flex-direction: column;
    align-items: stretch;
  }
  
  .position-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .comparison {
    flex-direction: column;
    gap: 15px;
  }
  
  .result-actions {
    flex-direction: column;
  }
}
</style>
